#region Using

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

#endregion

namespace SemanticEngine
{
	public static class XfnReader
	{

		private static readonly Regex PATTERN = new Regex("<a( [^>]*rel=\"me\"[^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
		private static readonly Regex HREF = new Regex("href=\"([^\"]*)\"", RegexOptions.IgnoreCase | RegexOptions.Compiled);

		public static List<Uri> FindLinks(Uri url)
		{
			string html = WebHelper.DownloadWebPage(url);
			return FindLinks(html);
		}

		/// <summary>
		/// Finds semantic links in a given HTML document.
		/// </summary>
		/// <param name="type">The type of link. Could be foaf, apml or sioc.</param>
		/// <param name="html">The HTML to look through.</param>
		/// <returns></returns>
		private static List<Uri> FindLinks(string html)
		{
			MatchCollection matches = PATTERN.Matches(html);
			List<Uri> urls = new List<Uri>();

			foreach (Match match in matches)
			{
				if (match.Groups.Count == 2)
				{
					string link = match.Groups[1].Value;
					Match hrefMatch = HREF.Match(link);

					if (hrefMatch.Groups.Count == 2)
					{
						Uri url;
						string value = hrefMatch.Groups[1].Value;
						if (Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out url) && !urls.Contains(url))
						{
							urls.Add(url);
						}
					}
				}
			}

			return urls;
		}
	}
}
